import { ipcMain } from 'electron';
import sqlite3, { Database } from "sqlite3";
import path from "node:path";

let db: Database;

function initPatientsDatabase(): void {
    const dbPath = path.join(process.cwd(), 'patients.db');

    db = new sqlite3.Database(dbPath, (err: Error | null) => {
        if (err) {
            console.error('Database opening error:', err.message);
            return;
        }

        console.log('Database connected successfully');

        db.run(
            `CREATE TABLE IF NOT EXISTS patients (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL,
                gender TEXT NOT NULL,
                diagnosis TEXT NOT NULL,
                admissionDate DATETIME NOT NULL,
                status TEXT NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )`,
            (createTableErr: Error | null) => {
                if (createTableErr) {
                    console.error('Table creation error:', createTableErr.message);
                } else {
                    console.log('Table "patients" created/verified');
                }
            }
        );
    });
}

// CRUD Operations for Patients
ipcMain.handle('create-patient', async (event, patient) => {
    return new Promise((resolve, reject) => {
        const sql = `INSERT INTO patients 
                    (name, age, gender, diagnosis, admissionDate, status) 
                    VALUES (?, ?, ?, ?, ?, ?)`;

        const params = [
            patient.name,
            patient.age,
            patient.gender,
            patient.diagnosis,
            patient.admissionDate,
            patient.status || 'stable'
        ];

        db.run(sql, params, function(err) {
            if (err) reject(err);
            resolve(this.lastID);
        });
    });
});

ipcMain.handle('read-patients', async () => {
    return new Promise((resolve, reject) => {
        const sql = 'SELECT * FROM patients ORDER BY created_at DESC';
        db.all(sql, [], (err, rows) => {
            if (err) reject(err);
            resolve(rows);
        });
    });
});

ipcMain.handle('update-patient', async (event, patient) => {
    return new Promise((resolve, reject) => {
        const sql = `UPDATE patients 
                    SET name = ?, age = ?, gender = ?, 
                        diagnosis = ?, admissionDate = ?, status = ? 
                    WHERE id = ?`;

        const params = [
            patient.name,
            patient.age,
            patient.gender,
            patient.diagnosis,
            patient.admissionDate,
            patient.status,
            patient.id
        ];

        db.run(sql, params, (err) => {
            if (err) reject(err);
            resolve(true);
        });
    });
});

ipcMain.handle('delete-patient', async (event, id) => {
    return new Promise((resolve, reject) => {
        const sql = 'DELETE FROM patients WHERE id = ?';
        db.run(sql, [id], (err) => {
            if (err) reject(err);
            resolve(true);
        });
    });
});

ipcMain.handle('search-patients', async (event, keyword) => {
    return new Promise((resolve, reject) => {
        const searchTerm = `%${keyword}%`;
        db.all(
            `SELECT * FROM patients
             WHERE name LIKE ? OR diagnosis LIKE ? OR status LIKE ?`,
            [searchTerm, searchTerm, searchTerm],
            (err, rows) => {
                if (err) reject(err);
                resolve(rows);
            }
        );
    });
});

export { initPatientsDatabase, db };

